import json
import glob
from Label_Enhancer_Opencv import *

def load_path(init_file_path=None):
    result = {}
    paths = {}
    json_path = None
    if len(glob.glob(r'init.json')) > 0:
        json_path = glob.glob(r'init.json')[0]
    elif len(glob.glob(r'*.json')) > 0:
        json_path = glob.glob(r'*.json')[0]
        
    if json_path is None:
        print('No init file')
    else:
        with open(json_path, 'r') as json_file:
            paths = json.load(json_file)
        print('Initialize from \"%s\"'%json_path)
    for key in ['read', 'write']:
        if (not key in paths.keys()) or (paths[key] is None):
            result[key] = None
        elif os.path.exists(paths[key]):
            result[key] = paths[key]
            print('%s path: \"%s\"'%(key, paths[key]))
        else:
            result[key] = None
    with open('init.json', 'w') as json_file:
        json.dump(result, json_file)
    return result
    
def update_path(paths, init_file_path=None):
    with open('init.json', 'w') as json_file:
        json.dump(paths, json_file)

def makedata(path, pic_original=None, colorLow=[0, 0, 0], colorHigh=[255, 255, 255]):
    pic_list = []
    if pic_original is None:
        pic_list = glob.glob(os.path.join(path, '*.jpg'))
        if pic_list == 0:
            return None
        pic_original = cv2.imread(pic_list[0])
    pic_analysis, pic_all, pic_r, pic_g, pic_b, data = EqualizeHist(pic_original)
    pic_mask, pic_mask_reverse = ColorFilter(pic_original, colorLow=colorLow, colorHigh=colorHigh)
    return pic_original, pic_analysis, pic_all, pic_r, pic_g, pic_b, pic_mask, pic_mask_reverse, data, pic_list